﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OS.Instructions
{
    class PrintData : Instruction
    {
        public PrintData()
        {
        }//end default constructor

        /// <summary>
        /// Executes the the PD instruction
        /// </summary>
        public override void ExecutePDInstruction()
        {
            Trace.WriteToTrace("Attempting to execute instruction: " + QueueManager.readyQueue.Peek().register_IR);

            //check to see if lines printed is greater than max lines allowed
            if (QueueManager.readyQueue.Peek().lines > QueueManager.readyQueue.Peek().maxLines)
            {
                QueueManager.readyQueue.Peek().terminationType = Termination.LineLimit;
            }
            else
            {
                int virtualAddress = int.Parse(QueueManager.readyQueue.Peek().register_IR[2].ToString() + QueueManager.readyQueue.Peek().register_IR[3].ToString());
                int page = virtualAddress / 10;

                if (QueueManager.readyQueue.Peek().TLB.ContainsKey(page))
                {
                    //what type is it
                    if (QueueManager.readyQueue.Peek().TLB[page] is Frame)
                    {
                        //move to IO Queue
                        CPU.SI = 2;
                        Trace.WriteToTrace("Setting SI to 2 to request IO.");
                    }
                    else if (QueueManager.readyQueue.Peek().TLB[page] is Track)
                    {
                        Track trk = (Track)QueueManager.readyQueue.Peek().TLB[page];

                        //move to swap queue
                        Trace.WriteToTrace("Need to swap track " + trk.TrackID + " into memory.");
                        Trace.WriteToTrace("Setting PI to 3 to request swap.");
                        CPU.PI = 3;
                    }
                }
                else
                {
                    QueueManager.readyQueue.Peek().terminationType = Termination.InvalidPageFault;
                }
            }

        }//end ExecuteInstruction
    }//end PrintData
}//end OS.Instructions
